<template>
  <div class="main-back">
    <MainTitle :main-title="mainTitle" />
    <dv-loading v-show="runFlag" class="loading">Loading...</dv-loading>
    <div :class="['gif-bg', {hide : !processFlag}]" />
    <div class="main-item">
      <div class="item item-current">
        <div class="tag-item">
          <tag-card v-for="(item,index) in itemdata" :key="index" ref="tag-card" class="tag-card" :item="item" @setFlow="setFlow" />
        </div>
        <main-charts>
          <div v-show="hasNoData" class="no-data">暂无数据</div>
          <div v-for="(item, index) in eqmList" :key="index" class="main-body">
            <eqm-card class="eqm-card" :is-result="false" :eqm="item" :index="index+1" />
          </div>
        </main-charts>
      </div>
      <div class="item item-result">
        <div v-show="!processFlag" class="result-control">
          <div v-if="!aiResult.value && aiResult.value!==0" class="item-result-title">人工智能大数据模型</div>
          <div v-else class="result">
            <div v-if="!processFlag && parseFloat(optimizationRate) && parseFloat(optimizationRate)>0">
              <div class="result-title">预计能耗节约：<span>{{ savingEnergy }}</span></div>
              <div class="result-detail">历史耗电量：{{ historyElec }}kWh</div>
              <div class="result-detail">优化耗电量：{{ optimizeElec }}kWh</div>
            </div>
            <div v-else-if="!processFlag && (parseFloat(optimizationRate)<0 || parseFloat(optimizationRate)===0)" class="result-best">太棒了！当前开机模式已经是最佳。</div>
            <diV v-else class="result-best">获取数据出错</diV>
          </div>
          <el-button type="primary" class="item-button" :disabled="runFlag" @click="getChillerSuggestionResult">运行</el-button>
        </div>
      </div>
      <div class="item item-suggest">
        <div class="button-group">
          <el-button :class="['system-button', system === 'lowChillWater' ? 'system-button-selected': '']" type="primary" @click="setSystem('lowChillWater')">低温冰机系统</el-button>
          <el-button :class="['system-button', system === 'mediumChillWater' ? 'system-button-selected' :'']" type="primary" @click="setSystem('mediumChillWater')">中温冰机系统</el-button>
        </div>
        <main-charts>
          <div v-show="hasNoData" class="no-data">暂无数据</div>
          <div v-for="(item, index) in suggestionResult" :key="index" class="main-body">
            <eqm-card class="eqm-card" :is-result="true" :eqm="item" :index="index+1" />
          </div>
        </main-charts>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { data } from './data/itemcard.json'
import initData from './data/initData.json'
import 'element-ui/lib/theme-chalk/index.css'
export default {
  components: {
    MainTitle: () => import('@/components/MainTitle.vue'),
    EqmCard: () => import('./module/EqmCard.vue'),
    TagCard: () => import('./module/tagCard.vue'),
    MainCharts: () => import('./module/mainCharts.vue')
  },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      systemMap: { 'hcda': 'HCDA', 'lcda': 'LCDA', 'lowChillWater': '低温冰机系统',
        'mediumChillWater': '中温冰机系统' },
      itemdata: data,
      initData: initData,
      eqmList: [],
      eqmResultList: [],
      originFlow: null,
      settedFlow: null,
      aiResult: {
        payload: []
      },
      system: 'lowChillWater',
      runFlag: false,
      hasNoData: false,
      processFlag: false,
      savingEnergy: null,
      historyElec: null,
      optimizeElec: null,
      PerSettedElec: null,
      optimizationRate: null
    }
  },
  computed: {
    mainTitle() {
      return '智慧节能-' + this.title
    },
    ...mapState({
      service: state => state.service,
      webModel: state => state.authentication.webModel,
      treeTemplate: state => state.component.treeTemplate
    }),
    originElec() {
      return this.itemdata.find(e => e.type === 'elec').value ? this.itemdata.find(e => e.type === 'elec').value : null
    },
    PerOriginElec() {
      return (this.originElec / this.originFlow).toFixed(2)
    },
    suggestInit() {
      const tmp = { 'status': 2, 'load': '' }
      return this.eqmResultList.map(e => ({ ...e, ...tmp }))
    },
    suggestionResult() {
      return this.suggestInit.map(e => ({ ...e, ...(this.aiResult.payload || []).find(i => i.id === e.id), name: e.name }))
    }
  },
  created() {
    this.init('lowChillWater')
  },

  methods: {
    setSystem(system) {
      this.system = system
      this.init(system)
    },
    async init(system) {
      this.runFlag = true
      this.loading = 0
      this.aiResult = {
        payload: []
      }
      try {
        const result = await this.service.getEnergyChillerMachineStatus({ 'id': system })
        if (!result.flag || !result.data) {
          this.runFlag = false
          this.hasNoData = true
          return
        }
        const array = this.initData[this.system].map(e => ({ ...e, ...(result.data || []).find(i => i.id === e.id) }))
        this.eqmResultList = array
        this.eqmList = array
        this.hasNoData = !(this.eqmList && this.eqmList.length)
        const machineHourlyResult = await this.service.getEnergyChillerStatus({ 'id': system })
        if (!machineHourlyResult.flag || !machineHourlyResult.data) {
          this.runFlag = false
          return
        }
        const hourlyResult = machineHourlyResult.data
        let elec = '25753'
        let flow = '29845'
        hourlyResult.forEach(e => {
          if (e.tag_id === 'p') {
            elec = e.value ? e.value.toFixed(2) : '-'
          }
          if (e.tag_id === 'lf') {
            flow = e.value ? e.value.toFixed(2) : '-'
            this.originFlow = e.value ? e.value.toFixed(2) : '-'
          }
        })
        this.itemdata = [
          {
            'type': 'elec',
            'name': '耗电功率',
            'value': elec
          },
          {
            'type': 'prod',
            'name': '制冷量',
            'value': flow
          }
        ]
        this.settedFlow = this.itemdata.find(e => e.type === 'prod') ? this.itemdata.find(e => e.type === 'prod').value : null
        this.runFlag = false
      } catch (e) {
        this.$notify({
          title: '请求失败',
          type: 'error',
          duration: 2500
        })
        this.runFlag = false
        this.hasNoData = true
      }
    },
    async getChillerSuggestionResult() {
      const flow = this.itemdata.find(e => e.type === 'prod')
      this.settedFlow = this.settedFlow && this.settedFlow !== '-' && flow ? this.settedFlow : flow.value
      if (this.system === 'mediumChillWater' && (this.settedFlow >= 26860 || this.settedFlow < 710)) {
        this.$notify({
          title: '制冷量不在能够实现的范围内，设置范围为：710~26860',
          type: 'error',
          duration: 2500
        })
        return
      }
      if (this.system === 'lowChillWater' && (this.settedFlow >= 8200 || this.settedFlow < 500)) {
        this.$notify({
          title: '制冷量不在能够实现的范围内，设置范围为：500~8200',
          type: 'error',
          duration: 2500
        })
        return
      }
      try {
        this.processFlag = true
        const requestParam = JSON.stringify({
          system: this.system,
          tag: {
            lf: parseInt(this.settedFlow),
            p: parseInt(this.originElec)
          }
        })
        const aiResult = await this.service.getChillerSuggestionResult(requestParam)
        this.aiResult = aiResult
        aiResult.value = Math.floor(aiResult.value)
        this.aiResult.value = aiResult.value
        this.PerSettedElec = (aiResult.value / this.settedFlow).toFixed(2)
        this.optimizationRate = ((this.PerOriginElec - this.PerSettedElec) / this.PerOriginElec * 100).toFixed(2)
        this.savingEnergy = this.optimizationRate !== 'NaN' ? this.optimizationRate + '%' : '-'
        this.historyElec = (this.settedFlow / this.originFlow * this.originElec).toFixed(0)
        this.optimizeElec = aiResult.value ? aiResult.value : '-'
        this.processFlag = false
      } catch (e) {
        this.processFlag = false
        this.$notify({
          title: '请求失败',
          type: 'error',
          duration: 2500
        })
      }
    },

    setFlow(e) {
      this.settedFlow = e.target.value
    },

    sleep(time) {
      return new Promise((resolve) => setTimeout(resolve, time))
    }
  }
}
</script>
<style lang="scss" scoped>
.main-back{
  display: flex;
  flex-flow: column nowrap;
  align-items: stretch;
  background-image: url('~@assets/report/bg.png');
  background-size: 100% 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
}
.item-current{
  width: 25%;
}
.item-result{
  position: relative;
}
.item-result .result-control{
    position: absolute;
    top: 55%;
    left: 50%;
    width: 14rem;
    height: 10rem;
    margin-left: -7rem;
    margin-top: -5rem;
    display: flex;
    flex-flow: column nowrap;
    justify-content: space-around;
}
.item-result-title{
  font-size: 1.4rem;
  padding-top: 0.5%;
  color: white;
  align-self: center;
}
.gif-bg{
  background: url('~@assets/report/bg2.gif') no-repeat top;
  background-size: 100% 100%;
  position: absolute;
  width: 90%;
  height: 77%;
  left: 5%;
  top: 10%;
}
.main-item{
  flex-grow: 1;
  display:flex;
  flex-flow: row nowrap;
  justify-content: space-around;
  background: url('~@assets/report/bg2.png') no-repeat top;
  background-size: 100% 100%;
  position: absolute;
  width: 90%;
  height: 77%;
  left: 5%;
  top: 10%;
}
.item{
  flex-grow: 3;
  display: flex;
  flex-flow: column nowrap;
  height: 75vh;
  width: 33%;
}

.item-result{
  flex-grow: 1;
 display: flex;
 flex-flow: column nowrap;
 align-items: stretch;
 justify-content: flex-start;
}
.tag-item{
  margin-bottom: 33px;
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-start;
  color: #00f4ff;
  margin: 0 2%;
}
.tag-suggess{
  align-items: flex-end;
}

.item-button{
  width: 8.3rem;
  align-self: center;
  color: white;
  font-size: 1.4rem;
  background-color:transparent;
  border-color: #00f4ff;
  border-radius: 0%;
  margin-top: 5px;
}
.item-left{
  margin-left: auto;
}
.main-body{
  flex: 1;
  display: flex;
  flex-flow: row nowrap;
}
.result-loading{
  border: 0 !important;
}
.result{
  height: 6rem;
  color: #fff;
  display:flex;
  flex-flow: column;
  justify-content: space-around;
  align-items:center;
}
.result-title{
  font-size: 1.2rem;
  font-weight: 600;
}
.result-title span{
  font-size: 1.3rem;
}
.result-best{
  font-size: 1.5rem;
  font-weight: 600;
  text-align: center;
}
.item-title{
  color: #fff;
  margin: 0;
}
.item-title.title1{
  text-align:right;
}
.item-title.title2{
  text-align:left;
  width: 60%;
}
.gif-bg.show{
  display: block;
}
.gif-bg.hide{
  display: none;
}

.button-group{
    flex:0;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    margin-bottom: 2.68rem;
    .system-button{
      font-size: 1rem;
      color:white;
      align-self: center;
      background-color:transparent;
      border: 0;
      border-radius: 0;
      padding: 12px 10px;
    }

  }
  .system-button-selected{
    background-color: #05417f !important;
  }
.item-suggest .main-charts{
  margin-top: 33px;
}
.no-data{
  position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    background: rgb(10,12,31);
    font-size: 20px;
    text-align: center;
    padding-top: 10rem;
}
.loading{
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba($color: #333, $alpha: 0.7);
  z-index: 9;
}
</style>
